<template>
  <div>
    <img id="backgroundimg" :src="backgroundimg">
    <div class="main">
      <div class="header">
        <i style="cursor:pointer;display:flex;float:right;" class="fas fa-arrow-left"></i>
        <div class="notifications"><b>{{ msgList.length }}</b></div>
        <div class="center">
          <div>
            <img class="pfp" :src="defaultAvatar">
            <p id="pfpname">{{ dataConnection ? "已链接" : "未链接" }}</p>
          </div>
        </div>
      </div>
      <div class="content">
        <div style="padding:11px;" v-for="(item,index) in msgList">
          <div class="msg-btn-holder" v-if="item.type==='you'">
            <div class="receiver-msg msg-btn">
              <p>{{ item.msg }}</p>
            </div>
          </div>
          <div class="msg-btn-holder" v-if="item.type==='me'">
            <div class="sender-msg msg-btn">
              <p>{{ item.msg }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">

        <div class="menu">
          <div class="copyText" @click="copyShare">
            <svg t="1703237452218" class="icon" viewBox="0 0 1084 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="6311" width="30" height="30">
              <path
                  d="M707.764706 514.228706a255.337412 255.337412 0 1 1 0-510.674824 255.337412 255.337412 0 0 1 0 510.674824z m0-60.235294a195.102118 195.102118 0 1 0 0-390.204236 195.102118 195.102118 0 0 0 0 390.204236z"
                  fill="#1296db" p-id="6312"></path>
              <path
                  d="M566.633412 54.633412l-25.901177 54.39247a177.272471 177.272471 0 1 0 35.418353 298.164706l37.948236 46.742588a237.507765 237.507765 0 1 1-47.465412-399.36z"
                  fill="#1296db" p-id="6313"></path>
              <path
                  d="M921.238588 503.928471a30.117647 30.117647 0 1 1-26.804706 53.910588 420.321882 420.321882 0 0 0-606.991058 376.711529 30.117647 30.117647 0 0 1-60.235295 0 480.557176 480.557176 0 0 1 694.031059-430.682353z"
                  fill="#1296db" p-id="6314"></path>
              <path
                  d="M545.852235 464.956235a30.117647 30.117647 0 0 1-14.095059 58.548706 334.607059 334.607059 0 0 0-413.214117 325.330824 30.117647 30.117647 0 1 1-60.235294 0A394.842353 394.842353 0 0 1 545.792 465.016471z"
                  fill="#1296db" p-id="6315"></path>
              <path
                  d="M996.773647 785.347765a30.117647 30.117647 0 0 1 0 60.235294h-241.302588a30.117647 30.117647 0 1 1 0-60.235294h241.302588z"
                  fill="#1296db" p-id="6316"></path>
              <path
                  d="M906.24 936.056471a30.117647 30.117647 0 1 1-60.235294 0v-241.242353a30.117647 30.117647 0 1 1 60.235294 0v241.302588z"
                  fill="#1296db" p-id="6317"></path>
            </svg>
          </div>
          <div @click="selectFile">
            <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
            <svg t="1703237409637" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="5262" width="30" height="30">
              <path
                  d="M853.333333 298.666667v512H170.666667V213.333333h221.866666l42.666667 42.666667H853.333333v42.666667zM256 341.333333v384h512V341.333333H256z m298.666667 256h170.666666v85.333334h-170.666666v-85.333334z"
                  fill="#1296db" p-id="5263"></path>
            </svg>
          </div>
        </div>

        <div style="width:100%;padding:11px;">
          <input placeholder="输入消息" class="text-box" name="message" v-model="msg">
          <div class="send-ico" @click="sendMsg">
            <svg t="1703237212374" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="4220" width="30" height="30">
              <path d="M128.37 832L896 512 128.37 192 128 440.89 676.57 512 128 583.11z" fill="#1296db"
                    p-id="4221"></path>
            </svg>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import defaultAvatar from '../assets/cat-551554_960_720.jpg'
import backgroundimg from '../assets/bg.jpg'
import {onMounted, reactive, ref} from "vue";
import Peer from "peerjs";
import {useRoute} from "vue-router";

const route = useRoute()
import Clipboard from 'clipboard';
import {mergeArrayBuffersToBlob, sliceFile} from "../util/FileUtil.js";
import {saveAs} from 'file-saver';

const shareUserId = ref("")
const msg = ref("")
const dataConnection = ref(null)

const msgList = ref([])

const fileList = reactive(new Map());

const peerInfo = reactive({
  peerId: "",
})

const peer = new Peer();

peer.on("open", function (id) {
  peerInfo.peerId = id
  if (shareUserId.value) {
    connect()
  }
})

//被连接的回调
peer.on("connection", (conn) => {
  conn.on("data", (data) => {
    onMessage(data)
  });
  conn.on("open", () => {
    dataConnection.value = conn
  });
});


const connect = () => {
  dataConnection.value = peer.connect(shareUserId.value);
  //连接对方的回调
  dataConnection.value.on("open", () => {
    console.log("连接成功");
  })
  dataConnection.value.on("data", (data) => {
    onMessage(data)
  });
}


const onMessage = (data) => {
  //文本聊天
  if (data.type === 1) {
    msgList.value.push({id: data.id, type: "you", msg: data.data})
  }
  //文件传输
  if (data.type === 2) {
    let r = data.data
    let newVar = fileList.get(data.id);
    if (newVar) {
      newVar.push(r.buff)
      updateMessage(data.id, "接收文件:" + r.fileName + "、完成进度：" + newVar.length + "/" + r.size)
    } else {
      fileList.set(data.id, [r.buff])
      newVar = fileList.get(data.id)
      msgList.value.push({
        id: data.id,
        type: "you",
        msg: "接收文件:" + r.fileName + "、完成进度：" + newVar.length + "/" + r.size
      })
    }
    if (newVar.length === r.size) {
      let mergedBlob = mergeArrayBuffersToBlob(newVar)
      saveAs(mergedBlob, r.fileName);
    }
  }
}

// 更新数组中的对象元素
function updateMessage(id, newMessage) {
  const index = msgList.value.findIndex(item => item.id === id);
  if (index !== -1) {
    // 更新对象元素的属性
    msgList.value[index].msg = newMessage;
    // 触发 UI 更新
    msgList.value = [...msgList.value];
  }
}

const buildMsg = (id, type, data) => {
  return {id, type, data}
}


const sendMsg = () => {
  if (dataConnection.value) {
    let id = randomString();
    dataConnection.value.send(buildMsg(id, 1, msg.value))
    msgList.value.push({id: id, type: "me", msg: msg.value})
    msg.value = "";
  }
}

const copyShare = () => {
  if (shareUserId.value){
    alert("你是好友只能加入，不能分享，需要分享，请进入主页地址。")
    return
  }


  let protocol = window.location.protocol;
// 获取 host
  let host = window.location.host;
  new Clipboard('.copyText', {
    text: () => protocol + "//" + host + "/?shareUserId=" + peerInfo.peerId,
  });
  alert("分享地址已经复制")
}


onMounted(() => {
  shareUserId.value = route.query.shareUserId
})

const fileInput = ref(null);
const selectFile = () => {
  fileInput.value.click();
}
const handleFileChange = (event) => {
  const file = event.target.files[0];
  sliceFile(file, 1024 * 200).then(files => {
    let id = randomString();
    for (let i = 0; i < files.length; i++) {
      let buildMsg1 = buildMsg(id, 2, {fileName: file.name, buff: files[i], size: files.length});
      if (i === 0) {
        msgList.value.push({
          id: id,
          type: "me",
          msg: "发送文件：" + file.name + "、完成进度：" + (i + 1) + "/" + files.length
        })
      } else {
        updateMessage(id, "发送文件：" + file.name + "、完成进度：" + (i + 1) + "/" + files.length)
      }
      dataConnection.value.send(buildMsg1)
    }
  })
}
const randomString = () => Math.random().toString(36).substring(2);

</script>

<style scoped>


body {
  margin: 0;
  font-size: 12px;
}

@keyframes zoom {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

#backgroundimg {
  object-fit: cover;
  object-position: center center;
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: -1;
  animation: zoom 20s infinite alternate;
}

.main {
  background-color: rgba(255, 255, 255, 0.04);
  aspect-ratio: 10/16;
  width: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 30px;
  backdrop-filter: blur(4px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
  transition: transform 1s ease, width 1s ease;
}

.main:hover {
  width: 410px;
}

.header {
  color: #fff;
  display: flex;
  padding: 20px;
  align-items: center;
}

#pfpname {
  transition: letter-spacing 0.3s ease;
}

#pfpname:hover {
  letter-spacing: 2px;
}

.notifications {
  background: #2796db;
  border-radius: 100%;
  aspect-ratio: 1;
  width: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 5px;
  cursor: pointer;
  transition: transform 2s ease;
}

.notifications:hover {
  transition: transform 2s ease;
}

.header .pfp {
  aspect-ratio: 1;
  width: 40px;
  border-radius: 100%;
  cursor: pointer;
  transition: transform 1s ease;
}

.pfp:hover {
  transform: scale(1.2);
}

.header .center {
  display: flex;
  justify-content: center;
  text-align: center;
  width: 100%;
}

.header .center div p {
  margin: 0;
  font-weight: 700;
}

.footer {
  width: 100%;
  height: 100px;
  position: fixed;
  bottom: 0;
  display: inline-flex;
  align-items: center;
}

.text-box {
  float: right;
  border-radius: 100px;
  border: 1px solid rgba(255, 255, 255, 0.6);
  background: none;
  padding: 8px 10px;
  width: 65%;
  outline: none;
  color: #fff;
  transition: transform 1s ease, width 1s ease;
}

.text-box:hover {
  width: 75%;
}

.send-ico {
  color: #fff;
  position: absolute;
  right: 0;
  border-radius: 100%;
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.text-box::placeholder {
  color: #c6c6c6;
  font-family: BraahOne;
}

.content {
  width: 100%;
  bottom: 100px;
  position: absolute;
  height: 450px;
  text-align: center;
  color: #afafaf;
  overflow: auto;
}

.msg-btn {
  color: #fff;
  word-wrap: break-word;
  border-radius: 100px;
  display: inline-block;
  max-width: 100%;
  font-size: 14px;
  font-family: "BraahOne";
}

.msg-btn p {
  padding: 10px 15px;
  margin: 0;
}

.msg-btn-holder {
  padding-bottom: 30px;
  width: 100%;
  margin-top: 10px;
}

.receiver-msg {
  background: #4c4c4c;
  float: left;
  text-align: left;
}

.sender-msg {
  background: #2798fc;
  float: right;
}

@keyframes rotate {
  from {
    rotate: 0deg;
  }

  50% {
    scale: 1 1.5;
  }

  to {
    rotate: 360deg;
  }
}

.menu {
  padding: 10px;
  width: 30%;
  display: flex;
  justify-content: space-between;
  color: #ffffff;
}
</style>
